package com.brycen.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 异步非阻塞IO，这里只演示了异步非阻塞的FileChannel
 * 注：没有异步阻塞IO，既然都异步了，再阻塞就没有任何意义了
 */
public class AioFileChannel {
    public static void main(String[] args) throws InterruptedException {
        try(AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("data.txt"), StandardOpenOption.READ)){
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            System.out.println("start read");
            channel.read(byteBuffer, 0, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println("read completed");
                    attachment.flip();
                    System.out.println(new String(attachment.array(),0,attachment.remaining()));
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.out.println("read failed");
                    exc.printStackTrace();
                }
            });
            System.out.println("read end");
            Thread.sleep(10000);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
